package com.funsport.controller.mobile;

import com.funsport.common.Result;
import com.funsport.entity.Order;
import com.funsport.entity.User;
import com.funsport.service.IOrderService;
import com.funsport.service.IUserService;
import com.funsport.service.WeChatPayService;
import com.funsport.security.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 移动端支付Controller
 */
@Slf4j
@RestController
@RequestMapping("/api/mobile/payment")
@RequiredArgsConstructor
@Tag(name = "移动端支付")
public class MobilePaymentController {
    
    private final WeChatPayService weChatPayService;
    private final IOrderService orderService;
    private final IUserService userService;
    
    @Operation(summary = "创建支付订单")
    @PostMapping("/create")
    public Result<Map<String, String>> createPayment(
            @RequestParam String orderType,
            @RequestParam Long businessId,
            @RequestParam BigDecimal amount,
            @RequestParam(required = false) String description
    ) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            
            // 1. 创建订单
            Order order = orderService.createOrder(userId, orderType, businessId, amount);
            
            // 2. 获取用户openid
            User user = userService.getById(userId);
            if (user == null || user.getOpenid() == null) {
                return Result.error("用户信息不完整");
            }
            
            // 3. 创建微信支付订单
            String desc = description != null ? description : "Fun-Sport " + orderType;
            Map<String, String> paymentParams = weChatPayService.createJsapiOrder(
                order.getOrderNo(),
                amount,
                desc,
                user.getOpenid()
            );
            
            // 4. 保存prepayId到订单
            order.setPrepayId(paymentParams.get("prepayId"));
            orderService.updateById(order);
            
            log.info("创建支付订单成功: 订单号={}, 用户ID={}", order.getOrderNo(), userId);
            
            // 5. 返回支付参数
            paymentParams.put("orderNo", order.getOrderNo());
            return Result.success("创建支付订单成功", paymentParams);
            
        } catch (Exception e) {
            log.error("创建支付订单失败: {}", e.getMessage(), e);
            return Result.error("创建支付订单失败: " + e.getMessage());
        }
    }
    
    @Operation(summary = "支付回调")
    @PostMapping("/callback")
    public String paymentCallback(@RequestBody String requestBody) {
        try {
            log.info("收到微信支付回调: {}", requestBody);
            
            // TODO: 解密回调数据
            // TODO: 验证签名
            // TODO: 更新订单状态
            // TODO: 处理业务逻辑（如确认预订）
            
            // 返回成功应答
            return "{\"code\":\"SUCCESS\",\"message\":\"成功\"}";
            
        } catch (Exception e) {
            log.error("处理支付回调失败: {}", e.getMessage(), e);
            return "{\"code\":\"FAIL\",\"message\":\"" + e.getMessage() + "\"}";
        }
    }
    
    @Operation(summary = "查询支付状态")
    @GetMapping("/query/{orderNo}")
    public Result<String> queryPayment(@PathVariable String orderNo) {
        try {
            Order order = orderService.getByOrderNo(orderNo);
            if (order == null) {
                return Result.error("订单不存在");
            }
            
            // 查询微信支付状态
            String status = weChatPayService.queryOrder(orderNo);
            
            return Result.success("查询成功", status);
            
        } catch (Exception e) {
            log.error("查询支付状态失败: {}", e.getMessage(), e);
            return Result.error("查询支付状态失败");
        }
    }
    
    @Operation(summary = "申请退款")
    @PostMapping("/refund/{orderNo}")
    public Result<Void> refund(
            @PathVariable String orderNo,
            @RequestParam(required = false) String reason
    ) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            
            Order order = orderService.getByOrderNo(orderNo);
            if (order == null) {
                return Result.error("订单不存在");
            }
            
            if (!order.getUserId().equals(userId)) {
                return Result.error("无权操作此订单");
            }
            
            if (!"paid".equals(order.getStatus())) {
                return Result.error("订单状态不支持退款");
            }
            
            // 申请退款
            weChatPayService.refund(orderNo, order.getAmount(), reason);
            
            // 更新订单状态
            orderService.updateRefundStatus(orderNo, order.getAmount(), reason);
            
            return Result.success("退款申请已提交", null);
            
        } catch (Exception e) {
            log.error("申请退款失败: {}", e.getMessage(), e);
            return Result.error("申请退款失败: " + e.getMessage());
        }
    }
    
    @Operation(summary = "获取我的订单列表")
    @GetMapping("/orders")
    public Result<?> getMyOrders(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize
    ) {
        // TODO: 实现订单列表查询
        return Result.success("功能开发中", null);
    }
}

